//
//  AppDelegate.m
//  XiXi
//
//  Created by HawkingWang on 16/9/29.
//  Copyright © 2016年 xi-xi.cc. All rights reserved.
//

#import "AppDelegate.h"
#import "WXApi.h"
#import "NetWorkManager.h"

#import "LaunchViewController.h"
#import "TabBarController.h"

@interface AppDelegate () <WXApiDelegate>

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [WXApi registerApp:WX_APP_ID withDescription:@"weixin"];
    
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor whiteColor];
    
    LaunchViewController *launch = [[LaunchViewController alloc] init];
    self.window.rootViewController = launch;
    
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    
    return YES;
}
// 这个方法是用于从微信返回第三方App
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url{
    return [WXApi handleOpenURL:url delegate:self];
}
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation{
    return [WXApi handleOpenURL:url delegate:self];
}

#pragma mark === WXApiDelegate ===
- (void)onReq:(BaseReq *)req{
    
}
//微信授权成功回调
- (void)onResp:(BaseResp *)resp{
    
    if ([resp isKindOfClass:[SendAuthResp class]]) {
        [SVProgressHUD show];
        SendAuthResp *temp = (SendAuthResp *)resp;
//        DLog(@"%@", temp.code);
        //用户取消微信授权
        if (!temp.code.length) {
            [SVProgressHUD dismiss];
            return;
    }
        /**https://api.weixin.qq.com/sns/oauth2/access_token?
        appid=APPID&
        secret=SECRET&
        code=CODE&
        grant_type=authorization_code
         */
        NSDictionary *para = @{
                               @"appid" : WX_APP_ID,
                               @"secret" : WX_APP_Secret,
                               @"code" :  temp.code,
                               @"grant_type" : @"authorization_code"
                               };
        [NetWorkManager weChatrequestWithType:0 withMethodName:@"oauth2/access_token?" withParaments:para withSuccessBlock:^(NSDictionary *response) {
//            DLog(@"%@", response);
            NSDictionary *accessDict = [NSDictionary dictionaryWithDictionary:response];
            NSString *accessToken = [accessDict objectForKey:WX_ACCESS_TOKEN];
            NSString *openID = [accessDict objectForKey:WX_OPEN_ID];
            NSString *refreshToken = [accessDict objectForKey:WX_REFRESH_TOKEN];
            // 本地持久化，以便access_token的使用、刷新或者持续
            if (accessToken && ![accessToken isEqualToString:@""] && openID && ![openID isEqualToString:@""]) {
                [[NSUserDefaults standardUserDefaults] setObject:accessToken forKey:WX_ACCESS_TOKEN];
                [[NSUserDefaults standardUserDefaults] setObject:openID forKey:WX_OPEN_ID];
                [[NSUserDefaults standardUserDefaults] setObject:refreshToken forKey:WX_REFRESH_TOKEN];
                [[NSUserDefaults standardUserDefaults] synchronize]; // 命令直接同步到文件里，来避免数据的丢失
            }
            [self wechatLoginByRequestForUserInfo];

        } withFailureBlock:^(NSError *error) {
            DLog(@"error : %@", error);
            [SVProgressHUD dismiss];
        } progress:nil];
    }
}
// 获取用户个人信息（UnionID机制）
- (void)wechatLoginByRequestForUserInfo {
    NSString *accessToken = [[NSUserDefaults standardUserDefaults] objectForKey:WX_ACCESS_TOKEN];
    NSString *openID = [[NSUserDefaults standardUserDefaults] objectForKey:WX_OPEN_ID];
    // 请求用户数据
    NSDictionary *para = @{
                           @"access_token" : accessToken,
                           @"openid" : openID
                           };
    [NetWorkManager weChatrequestWithType:1 withMethodName:@"userinfo?" withParaments:para withSuccessBlock:^(NSDictionary *response) {
//        DLog(@"%@", response);
        
        NSDictionary *userDic = [NSDictionary dictionaryWithDictionary:response];
        //对应该app,openid是唯一的
        NSString *openid = [userDic objectForKey:@"openid"];
        //unionid是用户唯一的
        NSString *unionid = [userDic objectForKey:@"unionid"];
        if ([openid isEqualToString:WNYopenid]) {
            TabBarController *tab = [[TabBarController alloc] init];
            self.window.rootViewController = tab;
        }
        
        if ([unionid isEqualToString:WNYunionid]) {
            TabBarController *tab = [[TabBarController alloc] init];
            self.window.rootViewController = tab;
        }
        
        
    } withFailureBlock:^(NSError *error) {
        DLog(@"error : %@", error);
        [SVProgressHUD dismiss];
    } progress:nil];
}



- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


@end
